package cn.gan.loveofsoul.exception;

import cn.gan.loveofsoul.commons.result.ErrorMessage;
import cn.gan.loveofsoul.commons.result.Result;
import cn.gan.loveofsoul.commons.result.StatusCode;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description:
 * @Author: ganwh
 * @Since: 2023/10/9 16:01
 */
@RestControllerAdvice
public class ProjectExceptionAdvice {
    @ExceptionHandler(Exception.class)
    public Result doException(Exception ex){
        //记录日志
        //通知运维
        //通知开发
        ex.printStackTrace();
        if (ex instanceof BusinessException) {
            return new Result(((BusinessException) ex).getCode(), ex.getMessage());
        } else if (ex instanceof MethodArgumentNotValidException) {
            BindingResult result = ((MethodArgumentNotValidException) ex).getBindingResult();
            FieldError error = result.getFieldError();
            return new Result(StatusCode.BAD_REQUEST, error.getDefaultMessage());
        }
        return new Result(StatusCode.ERROR, ErrorMessage.SYSTEM_ERROR);
    }
}
